/**
 * 通过输入框与下拉框绑定，实现输入快速匹配查询到合适的选项
 */

( function( j )
{
	j.selects = {
		relate: function( sel, ipt )
		{
			ipt.keyup( {
				sel: sel
			}, j.selects._ipt_keyup_handler );

			sel.change( {
				ipt: ipt
			}, j.selects._sel_changed );
		},

		_ipt_keyup_handler: function( e )
		{
			var sel = e.data.sel;
			var kw = $( this ).val();

			sel.find( "option" ).each( function( idx )
			{
				if( $( this ).text().indexOf( kw ) != -1 )
				{
					sel.val( $( this ).val() );
					return false;
				}
			} );
		},

		_sel_changed: function( e )
		{
			var ipt = e.data.ipt;
			ipt.val( $( this ).find( "option:selected" ).text() );
		}
	};

	// 将 select 关联一个 input，来让 input 输入任何字符能模糊匹配合适的选项
	j.fn.relate = function( ipt )
	{
		j.selects.relate( this, ipt );
	};
} )( jQuery );
